package com.application.image;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.platform.annotation.Controller;
import com.platform.constant.ConstantInit;
import com.platform.mvc.base.BaseController;
import com.platform.tools.ToolString;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * XXX 管理
 * 描述：
 */
@Controller("/app/icon")
public class IconController extends BaseController {

    @SuppressWarnings("unused")
    private static Logger log = Logger.getLogger(IconController.class);

    private static String filePath = "/images/icon/";

    private static String baseUploadPath = PathKit.getWebRootPath() + File.separator + "files";

    public void index() {
        splitPage.setList(getIconList());
        render("/template/icon/list.html");
    }

    public static List<File> getIconList() {
        File dir = new File(baseUploadPath, filePath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        List<File> fileList = Arrays.asList(dir.listFiles());

        return fileList;
    }

    /**
     * 图片上传处理
     */
    public void save() {

        List<UploadFile> files = getFiles(filePath, PropKit.getInt(ConstantInit.config_maxPostSize_key), ToolString
                .encoding);

        File dir = new File(baseUploadPath, filePath);

        for (UploadFile file : files) {
            try {
                FileUtils.moveFile(file.getFile(), new File(dir, file.getOriginalFileName()));
            } catch (IOException e) {
                e.printStackTrace();
                log.error(this.getClass().getName() + ": " + e.getMessage());
            }
        }

        redirect("/shop/web/icon");
    }

    /**
     * 删除,根据文件名删除
     */
    public void delete() {
        File file = new File(baseUploadPath + filePath, getPara("name"));
        if (file.exists()) {
            file.delete();
            redirect("/shop/web/icon");
        } else {
            setAttr("mgs", "图片不存在或已删除");
            render("/common/error.html");
        }
    }

}
